package com.czy.owner.ui.message;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.MessageContactsAdapter;
import com.czy.owner.adapter.MessageGroupAdapter;
import com.czy.owner.adapter.SearchHistoryAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.DbHelper;
import com.czy.owner.db.SearchTable;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MessageContacts;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/7/21 0021.
 */
public class SearchMessageActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.et_message_search_keyword)
    EditText etKeyword;
    @BindView(R.id.iv_message_search_clean)
    ImageView ivClean;
    @BindView(R.id.tv_message_search_close)
    TextView tvCLose;

    @BindView(R.id.ll_message_search_history_title)
    LinearLayout llHistoryTitle;
    @BindView(R.id.tv_message_search_title)
    TextView tvTitle;
    @BindView(R.id.iv_remove_history)
    ImageView ivRemoveHistory;

    @BindView(R.id.ll_message_result_wrapper)
    LinearLayout llResult;
    @BindView(R.id.rv_message_search_result)
    RecyclerView rvResult;

    @BindView(R.id.ll_group_search_wrapper)
    LinearLayout llGroupWrapper;
    @BindView(R.id.rv_group_search_result)
    RecyclerView rvGroup;
    @BindView(R.id.ll_contact_search_wrapper)
    LinearLayout llContactWrapper;
    @BindView(R.id.rv_contact_search_result)
    RecyclerView rvContact;


    @BindView(R.id.ll_search_message_tips)
    LinearLayout llTips;


    private boolean isSearching = false;
    private DbManager db = null;
    private List<SearchTable> historyList = new ArrayList<>();

    private MessageGroupAdapter mGroupAdapter;
    private List<EMGroup> mGroupList = new ArrayList<>();
    private List<EMGroup> tmpGroupList = new ArrayList<>();
    private MessageContactsAdapter mContactsAdapter;
    private List<MessageContacts> mContactsList = new ArrayList<>();
    private List<MessageContacts> tmpContactsList = new ArrayList<>();
    private DiskLruCacheHelper cacheHelper;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_message_search;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
// 获取编辑框焦点
        etKeyword.setFocusable(true);
        //打开软键盘
        /*InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);*/
        db = DbHelper.getInstance().getDb();
        ivClean.setOnClickListener(this);
        tvCLose.setOnClickListener(this);
        etKeyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    searchMessage();
                }
                return false;
            }
        });
        etKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etKeyword.getText().toString().length() > 0) {
                    ivClean.setVisibility(View.VISIBLE);
                } else {
                    ivClean.setVisibility(View.GONE);
                }
            }
        });
        etKeyword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    searchMessage();
                }
                return false;
            }
        });

        ivRemoveHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    WhereBuilder builder = WhereBuilder.b("searchtype", "=", SearchTable.SEARCH_TYPE_MESSAGE).and("useraccount", "=", UserHelper.getInstance().getUserAccount());
                    db.delete(SearchTable.class, builder);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                initKeyWordHistory();
            }
        });
        initKeyWordHistory();
    }

    @Override
    protected void updateViews() {

    }


    private void initKeyWordHistory() {
        tvTitle.setText(getResources().getString(R.string.search_history));
        try {
            historyList = db.selector(SearchTable.class)
                    .where("searchtype", "=", SearchTable.SEARCH_TYPE_MESSAGE)
                    .and("useraccount", "=", UserHelper.getInstance().getUserAccount())
                    .orderBy("searchTime", true)
                    .limit(10)
                    .findAll();

        } catch (DbException e) {
            e.printStackTrace();
        }
        llGroupWrapper.setVisibility(View.GONE);
        llContactWrapper.setVisibility(View.GONE);

        if (historyList != null && historyList.size() > 0) {
            llTips.setVisibility(View.GONE);
            llHistoryTitle.setVisibility(View.VISIBLE);
            llResult.setVisibility(View.VISIBLE);
            ivRemoveHistory.setVisibility(View.VISIBLE);
            SearchHistoryAdapter mSearchAdapter = new SearchHistoryAdapter(this, historyList);
            mSearchAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<SearchTable>() {
                @Override
                public void onItemClick(int position, SearchTable o, View view) {
                    etKeyword.setText(o.getKeyWord());
                    searchMessage();
                }
            });
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
            rvResult.setLayoutManager(layoutManager);
            rvResult.setAdapter(mSearchAdapter);
            rvResult.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        } else {
            llHistoryTitle.setVisibility(View.GONE);
            llResult.setVisibility(View.GONE);
            ivRemoveHistory.setVisibility(View.GONE);
            llTips.setVisibility(View.VISIBLE);
        }
    }

    private void searchMessage() {
        if (isSearching) return;
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            imm.hideSoftInputFromWindow(etKeyword.getWindowToken(), 0);
        }
        final String searchKeyword = etKeyword.getText().toString().toString().trim();

        saveSearchKeyWord(searchKeyword);
        isSearching = true;
        mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));

        mGroupList = EMClient.getInstance().groupManager().getAllGroups();
        tmpGroupList = new ArrayList<>();
        for (int i = 0; i < mGroupList.size(); i++) {
            if (mGroupList.get(i).getGroupName().contains(searchKeyword)) {
                tmpGroupList.add(mGroupList.get(i));
            }
        }
        mGroupAdapter = new MessageGroupAdapter(SearchMessageActivity.this, tmpGroupList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(SearchMessageActivity.this);
        rvGroup.setLayoutManager(layoutManager);
        mGroupAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<EMGroup>() {
            @Override
            public void onItemClick(int position, EMGroup o, View view) {
                Intent intent = new Intent(SearchMessageActivity.this, ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, o.getGroupId());
                startActivityForResult(intent, 0);
            }
        });
        rvGroup.setAdapter(mGroupAdapter);
        rvGroup.addItemDecoration(new RecycleViewDivider(SearchMessageActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        String strData = null;
        if (cacheHelper != null) {
            strData = cacheHelper.getAsString(UserHelper.getInstance().getUserAccount() + "_contacts");
        }
        if ((int)SharedPreferencesUtils.getParam(SearchMessageActivity.this,UserHelper.getInstance().getUserAccount()+ Constants.SHARED_PREFERENCES_KEY_BINDSTOREID,0) != 0 || TextUtils.isEmpty(strData)) {
            RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ADDRESS_BOOK);
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(SearchMessageActivity.this).getSession());
            params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(SearchMessageActivity.this,UserHelper.getInstance().getUserAccount()+ Constants.SHARED_PREFERENCES_KEY_BINDSTOREID,0)+"");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(SearchMessageActivity.this, result);
                    if (data != null) {
                        DiskLruCacheHelper cacheHelper = null;
                        try {
                            cacheHelper = new DiskLruCacheHelper(SearchMessageActivity.this);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (cacheHelper != null) {
                            cacheHelper.put(UserHelper.getInstance().getUserAccount() + "_contacts", data, 3600);
                        }
                        Gson gson = new Gson();
                        mContactsList = gson.fromJson(data, new TypeToken<List<MessageContacts>>() {
                        }.getType());
                        showContactsList();

                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    isSearching = false;
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    isSearching = false;
                    mLoadView.CancleLoadView();
                }
            });
        } else {
            isSearching = false;
            showContactsList();
            mLoadView.CancleLoadView();
        }
    }

    private void showContactsList() {
        final String searchKeyword = etKeyword.getText().toString().toString().trim();
        tmpContactsList = new ArrayList<>();
        for (int i = 0; i < mContactsList.size(); i++) {
            if (mContactsList.get(i).getEmployeesName().contains(searchKeyword)) {
                tmpContactsList.add(mContactsList.get(i));
            }
        }
        mContactsAdapter = new MessageContactsAdapter(SearchMessageActivity.this, tmpContactsList);
        mContactsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MessageContacts>() {
            @Override
            public void onItemClick(int position, MessageContacts o, View view) {
                Intent intent = new Intent(SearchMessageActivity.this, ContactsPanelActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                startActivity(intent);
            }
        });
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(SearchMessageActivity.this);
        rvContact.setLayoutManager(layoutManager);
        rvContact.setAdapter(mContactsAdapter);
        rvContact.addItemDecoration(new RecycleViewDivider(SearchMessageActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        checkSearchResult(searchKeyword);
    }

    private void saveSearchKeyWord(String keyWord) {
        if (TextUtils.isEmpty(keyWord)) {
            return;
        }
        try {
            SearchTable tmpSearch = db.selector(SearchTable.class).where("keyword", "=", keyWord).and("searchtype", "=", SearchTable.SEARCH_TYPE_MESSAGE).and("useraccount", "=", UserHelper.getInstance().getUserAccount()).findFirst();

            if (tmpSearch == null) {
                SearchTable search = new SearchTable();
                search.setKeyWord(keyWord);
                search.setSearchType(SearchTable.SEARCH_TYPE_MESSAGE);
                search.setSearchTime(System.currentTimeMillis());
                search.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.saveOrUpdate(search);
            } else {
                tmpSearch.setKeyWord(keyWord);
                tmpSearch.setSearchType(SearchTable.SEARCH_TYPE_MESSAGE);
                tmpSearch.setSearchTime(System.currentTimeMillis());
                tmpSearch.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.update(tmpSearch);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void checkSearchResult(String keyWord) {
        llTips.setVisibility(View.GONE);
        llResult.setVisibility(View.GONE);
        if (tmpGroupList.size() + tmpContactsList.size() > 0) {
            llHistoryTitle.setVisibility(View.GONE);
            if (tmpGroupList.size() > 0) {
                llGroupWrapper.setVisibility(View.VISIBLE);
            } else {
                llGroupWrapper.setVisibility(View.GONE);
            }
            if (tmpContactsList.size() > 0) {
                llContactWrapper.setVisibility(View.VISIBLE);
            } else {
                llContactWrapper.setVisibility(View.GONE);
            }
        } else {
            llHistoryTitle.setVisibility(View.VISIBLE);
            tvTitle.setText("暂无相关结果:" + keyWord);
            ivRemoveHistory.setVisibility(View.GONE);
            llGroupWrapper.setVisibility(View.GONE);
            llContactWrapper.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_message_search_clean:
                etKeyword.setText("");
                initKeyWordHistory();
                break;
            case R.id.tv_message_search_close:
                finish();
                break;
        }
    }
}

